<template>
    <ElDialog v-model="isShow" title="附件列表" width="60%" @closed="handleFjlbClosed">
        <div style="display: flex; justify-content: flex-end; margin-bottom: 10px;">
            <ElUpload ref="uploadRef" class="upload-demo" :action="uploadUrl" :headers="uploadHeaders"
                :auto-upload="false" multiple :on-success="onSuccess">
                <template #trigger>
                    <el-button type="primary" :icon="Search">选择文件</el-button>
                </template>

                <el-button class="ml-3" type="success" :icon="Upload" @click="submitUpload"
                    style="margin-left: 12px;margin-top: -6px;">
                    上传文件
                </el-button>

                <el-button class="ml-3" type="danger" :icon="Delete" @click="uploadClear" style="margin-top: -6px;">
                    清空
                </el-button>

                <el-button class="ml-3" type="default" :icon="Refresh" @click="refreshFileList"
                    style="margin-top: -6px;">
                    刷新
                </el-button>
            </ElUpload>
        </div>
        <div class="file-drop-area" @paste="handlePaste" @dragover.prevent>
            <div class="drop-content">
                <p class="drop-text">点击直接粘贴文件或截图</p>
            </div>
            <input type="file" ref="fileInput" style="display: none" multiple>
        </div>
        <ElTable class="list-table is-border" height="700" :="$attrs" :data="fjList" border>
            <ElTableColumn label="文件名称" prop="sysFileEntity.fileName" align="center"></ElTableColumn>
            <ElTableColumn label="文件后缀名" prop="sysFileEntity.fileType" align="center"></ElTableColumn>
            <ElTableColumn prop="_action" label="操作" fixed="right" :min-width="90" header-align="center" align="center">
                <template #default="{ row }">
                    <ElButton type="primary" link @click="fileNewDownload(row)">下载</ElButton>
                    <ElButton type="primary" link @click="openFilewView(row)">预览</ElButton>
                    <ElButton type="primary" link @click="deleteFile(row)">删除</ElButton>
                </template>
            </ElTableColumn>
        </ElTable>
        <ElImageViewer v-if="previewVisible" @close="closePreview" :url-list="srcList_fileImg"
            :initial-index="selectedIndex" />

    </ElDialog>
</template>

<script setup lang="ts">
import { ElDialog, ElUpload, UploadInstance, ElInput, ElTableColumn, ElMessage, ElMessageBox } from 'element-plus';
import { computed, ref, reactive } from 'vue'
import {
    Delete, Upload, Search, Refresh
} from '@element-plus/icons-vue'
import { getFileListByGlId, postDownLoadFile, postDeleteFile } from '../api';
import { getFileExtension } from '@/utils/zeo'


const uploadRef = ref<UploadInstance>()
const fileInput = ref<HTMLInputElement | null>(null)
let uploadHeaders = reactive({ token: '' })
const fjList = ref([])

interface Props {
    fjObj;
}

const props = defineProps<Props>();

// 显示
const isShow = computed(() => {
    console.log("visible computed:", props.fjObj);
    const token = localStorage.getItem('token')
    uploadHeaders.token = token;
    getFileList();
    return props.fjObj.isShow;
});

// 上传附件的URL
const uploadUrl = computed(() => {
    return import.meta.env.VITE_APP_API_BASE_URL + '/new/ykf/fileNew/uploadFile?mklx=' + props.fjObj.mklx + '&glId=' + props.fjObj.gjjlId;
});

// 上传文件
const submitUpload = () => {
    uploadRef.value!.submit()
}

// 清空选中文件
const uploadClear = () => {
    uploadRef.value.clearFiles();
}

// 获取附件列表
const getFileList = async () => {
    let res = await getFileListByGlId({ mklx: props.fjObj.mklx, glId: props.fjObj.gjjlId });
    console.log(res);
    fjList.value = res;
}

// 刷新附件列表
const refreshFileList = async () => {
    await getFileList();
}

const emit = defineEmits(['sx-list'])

// 上传成功调用
const onSuccess = async (res) => {
    if (res.code === 0) {
        ElMessage.success('上传成功');
        await getFileList();
        if (uploadRef.value) {
            uploadRef.value.clearFiles()  // 清空已选文件列表
        }
        emit('sx-list')
    } else {
        ElMessage.warning(res.msg);
    }
}

const handlePaste = async (event) => {
    const items = event.clipboardData?.items || []

    for (const item of items) {
        console.log(item);
        const blob = item.getAsFile()
        if (!blob) continue

        const extension = getFileExtension(item.type)
        const fileName = `paste-${Date.now()}.${extension}`
        const file = new File([blob], fileName, { type: item.type })

        uploadRef.value?.handleStart(file)  // 添加到上传列表
    }
}

const fileNewDownload = async (row) => {
    const res = await postDownLoadFile(row);
    if (res.code === 0) {
        const link = document.createElement('a');
        link.href = res.msg;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
}


// 图片预览
const previewVisible = ref(false)
const selectedIndex = ref(0);
const srcList_fileObj = ref([])
const srcList_fileImg = ref([])

const openFilewView = async (row) => {
    const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg'];
    if (imageExtensions.includes(row.sysFileEntity.fileType)) {
        srcList_fileObj.value = [];
        srcList_fileImg.value = [];

        for (let i = 0; i < fjList.value.length; i++) {
            const fileType = fjList.value[i].sysFileEntity.fileType;
            if (imageExtensions.includes(`${fileType}`)) {
                srcList_fileObj.value.push(fjList.value[i]);
                srcList_fileImg.value.push(fjList.value[i].sysFileEntity.fileUrl);
            }
        }

        for (let i = 0; i < srcList_fileObj.value.length; i++) {
            if (srcList_fileObj.value[i].ykfFileId === row.ykfFileId) {
                selectedIndex.value = i;
                previewVisible.value = true;
                return;
            }
        }
    }

    window.open('http://47.96.100.131:8012/onlinePreview?url=' + encodeURIComponent(btoa(row.sysFileEntity.fileUrl)));
}

const deleteFile = async (row) => {
    await ElMessageBox.confirm('是否确定删除？', '提示')
    const res = await postDeleteFile(row);
    if (res.code === 0) {
        ElMessage.success('删除成功');
        await getFileList();
    } else {
        ElMessage.warning(res.msg);
    }
}

const closePreview = () => {
    previewVisible.value = false;
};

const handleFjlbClosed = () => {
    if (uploadRef.value) {
        props.fjObj.isShow = false;
        uploadRef.value.clearFiles()  // 清空已选文件列表
    }
}


</script>

<style scoped lang="scss">
.file-drop-area {
    border: 2px dashed var(--el-border-color);
    border-radius: 8px;
    padding: 30px;
    text-align: center;
    cursor: pointer;
    margin: 0 0 20px 0;
    /* 去掉auto，改为0 0 20px 0 表示只设置下边距 */
    transition: all 0.3s ease;
    background-color: var(--el-fill-color-light);
    width: 100px;
    /* 固定宽度 */
    height: 1px;
    /* 固定高度 */
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
        border-color: var(--el-color-primary);
        background-color: var(--el-fill-color-blank);
    }

    .drop-content {
        .upload-icon {
            font-size: 48px;
            color: var(--el-color-primary);
            margin-bottom: 12px;
        }

        .drop-text {
            font-size: 16px;
            font-weight: 500;
            margin-bottom: 8px;
            color: var(--el-text-color-primary);
        }
    }
}

/* 其他样式保持不变 */
.list-table {
    margin-top: 20px;
}

:deep(.centered-input .el-input__inner) {
    text-align: center;
}
</style>